<?php

namespace BookSpider;

/**
 * SpiderBook Abstract Class
 *
 * @package    SpiderBook
 * @subpackage Libraries
 * @author     sanli <sanli@qq.com>
 * @time       2016/04/11 22:20
 */
class Http {
    
    public $htm;
    private static $ch;
    
    public function __construct() {
        self::$ch = curl_init();
    }

    /**
     * Get a request result
     *
     * @param string $url
     * @param array  $header
     * @param int    $timeout
     * @return mixed
     */
    public static function get($url, $header = array(), $timeout = 5) {

        if(!self::$ch)
            self::$ch = curl_init();
        $default = array(
            'Accept'            => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding'   => 'gzip, deflate, sdch',
            'Accept-Language'   => 'zh-CN,zh;q=0.8',
            'Cache-Control'     => 'no-cache',
            'Connection' 	    => 'keep-alive',
            'Pragma' 		    => 'no-cache',
            'User-Agent'        => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36',
        );
        $header = array_merge($header, $default);

        curl_setopt (self::$ch, CURLOPT_URL, $url);
        curl_setopt (self::$ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt (self::$ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt (self::$ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $errno = curl_errno(self::$ch);
        if($errno) {
            $error = curl_error(self::$ch);
            return array('errno' => $errno, 'error' => $error);
        }
        $result = curl_exec(self::$ch);
        return $result;
    }

    public function __destruct () {
        
        curl_close(self::$ch);
    }
}